import { login, logout, getMenusByUserId } from '@/api/user'
import {  getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { MessageBox, Message } from 'element-ui'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    menuList: [],
    userObj:{}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENULIST: (state, menuList) => {
    state.menuList = menuList
  },
  SET_USEROBJ: (state, userObj) => {
    state.userObj = userObj
  }
}

const actions = {
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    const result = await login({ username: username.trim(), password: password })
    const { code, data, msg } = result
    if (code == '0000') {
      commit('SET_USEROBJ',data)
      const { id, username } = data //.roles[0]
      commit('SET_TOKEN', id)
      setToken(id)
      commit('SET_NAME', username)
      return 'ok'
    } else {
      return Message.error(msg)
    }
  },

  // 获取菜单
  getMenusByUserId({ commit, state }) {
    return new Promise((resolve, reject) => {
      getMenusByUserId({userId: state.token}).then(response => {
        const { code, data, msg } = response
        if(code !== '0000') return Message.error(msg)
        commit('SET_MENULIST',data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

